/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. */
package com.springframework.session;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * A {@link SessionRepository} backed by a {@link java.util.Map} and that uses a
 * {@link MapSession}. By default a
 * {@link java.util.concurrent.ConcurrentHashMap} is used, but a custom
 * {@link java.util.Map} can be injected to use distributed maps provided by
 * NoSQL stores like Redis and Hazelcast.
 *
 * <p>
 * The implementation does NOT support firing {@link SessionDeletedEvent} or
 * {@link SessionExpiredEvent}.
 * </p>
 *
 * @author Rob Winch
 * @since 1.0
 */
public class MapSessionRepository implements SessionRepository<Session> {
	/**
	 * If non-null, this value is used to override
	 * {@link ExpiringSession#setMaxInactiveIntervalInSeconds(int)}.
	 */
	private Integer defaultMaxInactiveInterval;

	private final Map<String, Session> sessions;

	/**
	 * Creates an instance backed by a
	 * {@link java.util.concurrent.ConcurrentHashMap}.
	 */
	public MapSessionRepository() {
		this(new ConcurrentHashMap<String, Session>());
	}

	/**
	 * Creates a new instance backed by the provided {@link java.util.Map}. This
	 * allows injecting a distributed {@link java.util.Map}.
	 *
	 * @param sessions
	 *            the {@link java.util.Map} to use. Cannot be null.
	 */
	public MapSessionRepository(Map<String, Session> sessions) {
		if (sessions == null) {
			throw new IllegalArgumentException("sessions cannot be null");
		}
		this.sessions = sessions;
	}

	/**
	 * If non-null, this value is used to override
	 * {@link ExpiringSession#setMaxInactiveIntervalInSeconds(int)}.
	 * 
	 * @param defaultMaxInactiveInterval
	 *            the number of seconds that the {@link Session} should be kept
	 *            alive between client requests.
	 */
	public void setDefaultMaxInactiveInterval(int defaultMaxInactiveInterval) {
		this.defaultMaxInactiveInterval = Integer.valueOf(defaultMaxInactiveInterval);
	}

	public void save(Session session) {
		this.sessions.put(session.getId(), new MapSession(session));
	}

	public Session getSession(String id) {
		Session saved = this.sessions.get(id);
		System.out.println("sessionId==>"+id);
		if (saved == null) {
			return null;
		}
		if (saved.isExpired()) {
			delete(saved.getId());
			return null;
		}
		return new MapSession(saved);
	}

	public void delete(String id) {
		this.sessions.remove(id);
	}

	public Session createSession() {
		Session result = new MapSession();
		if (this.defaultMaxInactiveInterval != null) {
			result.setMaxInactiveIntervalInSeconds(this.defaultMaxInactiveInterval);
		}
		return result;
	}
}
